<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>组合对话框预览</title>
        <#include "/pubHeadStyleTree.html">
        <script src="${ctx}/formStatic/form/CommonDialog.js"></script>
    </head>
    <body>
<div style="position: relative;height: 100%;overflow: hidden">
    <div class="ccpui-trees" style="bottom:60px;">
        <div style="margin-top: 6px;">
            <ul id="treeClass" class="ztree ccpui-listZtree" style="top:0"></ul>
        </div>
    </div>
    <div class="ccpui-coreContent formView">
        <table id="formDialogTable" lay-filter="formDialogTable"></table>
    </div>
</div>
<script type="text/html" id="customHeaderTool">
    <div class="layui-btn-container">
        <a class="layui-btn layui-btn-sm" lay-event="query">
            <i class="layui-icon layui-icon-search"></i>
            <span>查询</span>
        </a>
        <!--<div style="position: absolute;top: 600px;" id="combinationBtn">-->
            <!--<a class="layui-btn" lay-event="determine">-->
                <!--<span>确定</span>-->
            <!--</a>-->
            <!--<a class="layui-btn" lay-event="reset">-->
                <!--<span>重置</span>-->
            <!--</a>-->
            <!--<a class="layui-btn layui-btn-danger" lay-event="cancel">-->
                <!--<span>取消</span>-->
            <!--</a>-->
        <!--</div>-->
    </div>
    <form class="layui-form" action="" style="margin-top:10px;max-height: 200px;overflow: auto" lay-filter="formDef" id="queryForm">
        <input type="hidden" name="selectData">
        <input type="hidden" name="selectDataIds">
        <div class="table-top-filter" id="queryField" style="overflow-y: hidden">
        </div>
    </form>
</script>
<script>
    var combinationDialog;

    layui.config({
        base: serverPath.formPath + staticPath.formPath //静态资源所在路径
    }).extend({
         index: 'index' //主入口模块
    }).use(['index', 'table', 'layer', 'jquery', 'form', 'tree', 'commons', 'common', 'totalFilter', 'setter'], function () {
        var table = layui.table, layer = layui.layer, setter = layui.setter, commons = layui.commons,
            common = layui.common,
            totalFilter = layui.totalFilter, form = layui.form,$=layui.jquery;
        var combinationAlias = '${combinationAlias}';
        var isOpenJsonData = '${isOpenJsonData}';

        var selList = [];
        if(layui.selList) {
            selList.push.apply(selList,layui.selList);
        }

        $.ajax({
            url:serverPath.formPath + setter.formLinkPath + "formDialog/combinationDialog/edit",
            type:"post",
            dataType:'json',
            data:{"alias":combinationAlias},
            success:function (result) {
                combinationDialog = result.data;
                resZtrees(combinationDialog.treeDialog);
                loadTable(combinationDialog.listDialog);
            }
        });

        //加载左侧树形对话框
        function resZtrees(treeDialog) {
            var displayField = JSON.parse(treeDialog.displayfield);
            if (displayField != null) {
                var setting = {
                    async: {
                        enable: true,
                        url: serverPath.formPath + setter.formLinkPath + 'formDialog/getTreeData?alias=' + treeDialog.alias + '&isRoot=1',
                        autoParam: [displayField.id + "=idKey", displayField.pid + "=pidKey", displayField.displayName + "=nameKey"],
                        otherParam: {
                            idKeyName: displayField.id,
                            pidKeyName: displayField.pid,
                            nameKeyName: displayField.displayName
                        }
                    },
                    data: {
                        key: {name: displayField.displayName},
                        simpleData: {
                            enable: true,
                            idKey: displayField.id,
                            pIdKey: displayField.pid
                        }
                    },
                    check: {
                        enable: treeDialog.issingle === 0
                    },
                    callback: {
                        onClick: getTreeNodeClick
                    }
                };
                zTree = $.fn.zTree.init($('#treeClass'), setting);
            }
        }
        //树节点单击事件
        var combinationWhere = {};
        function getTreeNodeClick(event, treeId, treeNode) {
            //拼接where条件
            var combinationField = JSON.parse(combinationDialog.field);

            for(var index in combinationField){
                var treeFieldName = combinationField[index].tree.fieldName;
                var treeValue = treeNode[treeFieldName];
                var listWhereName = combinationField[index].list.fieldName;
                combinationWhere[listWhereName] = treeValue;
            }
            common.tableConditionRender("formDialogTable", "formDef", {where: combinationWhere}, false);
        }

        //加载右侧列表对话框
        function loadTable(listDialog) {
            //组装列表显示字段数据
            var displayField = JSON.parse(listDialog.displayfield);
            var isSingle = listDialog.issingle;
            var array = [];
            var checkboxField = {type: 'checkbox', fixed: 'left'};
            if (isSingle === 1) {
                checkboxField = {type: 'radio', fixed: 'left'};
            }
            array.push(checkboxField);
            for (var i = 0; i < displayField.length; i++) {
                var json = {};
                var fieldName = displayField[i].field;
                json.field = fieldName;
                json.title = displayField[i].comment;
                json.align = "center";
                array.push(json);
            }
            table.render({
                elem: '#formDialogTable'
                , url: serverPath.formPath + setter.formLinkPath + "formDialog/showTableData?alias="+listDialog.alias
                , title: '组合对话框'
                , height: combinationDialog.height - 113
                , defaultToolbar: []
                , autoSort: false
                , toolbar: '#customHeaderTool'
                , cols: [array]
                , page: true
                , done: function () {
                    table.resize();
                    //修改按钮组样式
                    var tableTool = $(".formView>div>div");
                    tableTool.css("padding-right",0);
                    tableTool.children(".layui-table-tool-temp").removeClass("layui-table-tool-temp");
                    $("#combinationBtn").css("top", (combinationDialog.height - 100) + 'px');
                    addSearchField(listDialog.conditionfield);
                }
                ,parseData: function (res) {
                    var _data = res.data;
                    //获取主键
                    var count=0;
                    var pkStr="ID";
                    for(var p in _data[0]){
                        count++;
                        var str = _data[0][p];
                        if(str != null && str != ""){
                            if(count == 1 && (str.length == 32 || str=='orgResourcesManager') && p.indexOf("ID")>0){
                                pkStr=p;
                                break;
                            }
                        }
                    }
                    if (_data.length > 0 && selList.length > 0) {
                        for (var i = 0; i < _data.length; i++) {
                            var _d = _data[i];
                            for (var j = 0; j < selList.length; j++) {
                                var _td = selList[j];
                                if (_d[pkStr] === _td.ID) {
                                    _d.LAY_CHECKED = true;
                                }
                            }
                        }
                    }
                }

            });
            totalFilter.init('formDialogTable');
            common.tableConditionRender("formDialogTable", "formDef", {where: {}}, true);
        }

        //头工具栏事件
        table.on('toolbar(formDialogTable)', function (obj) {
            switch (obj.event) {
                case 'query':
                    common.tableConditionRender("formDialogTable", "formDef", {where: {}}, false);
                    break;
            }
        });
        //搜索框
        function addSearchField(searchField){
            var searchArray = JSON.parse(searchField);
            for(var index in searchArray){
                var search = searchArray[index];
                if(search != null && search.defaultType === '1'){
                    var searchHtml = '<div class="table-filter-alone">' +
                        '<label class="layui-form-label outofHiding" title="'+search.comment+'">'+search.comment+'</label>';
                    //拼接name
                    var searchCondition = "";
                    var fieldHtml = "";
                    var searchFieldClass = "layui-input ";
                    if(search.fieldType === 'date'){
                        if(search.condition === '='){
                            searchCondition = "Q_" + search.field + "_DL";
                            searchFieldClass += "start_time";
                        }else if(search.condition === '>='){
                            searchCondition = "Q_start" + search.field + "_DL";
                            searchFieldClass += "start_time";
                        }else if(search.condition === '<='){
                            searchCondition = "Q_end" + search.field + "_DG";
                            searchFieldClass += "end_time";
                        }else{
                            fieldHtml = '<input type="text" name="Q_start' + search.field + '_DL" class="layui-input filter-value start_time"/>' +
                                ' <label class="layui-form-label">到:</label>' +
                                ' <input type="text" name="Q_end' + search.field + '_DG" class="layui-input filter-value end_time"/>';
                        }
                    }else if(search.fieldType === 'number'){
                        searchCondition = "Q_" + search.field + "_DB";
                    }else{
                        if(search.paraCt === '1'){
                            searchFieldClass += "filter-value ";
                            if(search.condition === "="){
                                searchCondition = "Q_" + search.field + "_S";
                            }else if(search.condition === "like" || search.condition === "likeEnd"){
                                searchCondition = "Q_" + search.field + "_SL";
                            }
                        }else {
                            searchCondition = search.field;
                            var chooseClick = "";
                            switch (search.paraCt) {
                                case "0":
                                    chooseClick = 'selectCustomDialog(this);" id="dialog" dialog="' + search.dialog + '" param="' + search.param + '"';
                                    break;
                                case "4":
                                    chooseClick = "selectUser(this);";
                                    break;
                                case "17":
                                    chooseClick = "selectRole(this);";
                                    break;
                                case "18":
                                    chooseClick = "selectOrg(this);";
                                    break;
                                case "19":
                                    //岗位
                                    chooseClick = "selectUser(this);";
                                    break;
                                default:
                            }
                            fieldHtml = '<input type="text" readonly="readonly" class="layui-input filter-value" name="' + searchCondition + '">' +
                                '<input type="button" class="layui-btn layui-btn-sm" value="选择" onclick="' + chooseClick + '" style="margin: 4px;width:48px;">';
                        }
                    }
                    if(fieldHtml === ""){
                        fieldHtml = '<input type="text" name="'+searchCondition+'" class="'+ searchFieldClass +'" placeholder="'+search.comment+'" autocomplete="off"/>';
                    }
                    searchHtml += fieldHtml + '</div>';



                    var queryField = $("#queryField");
                    //检查查询条件是否存在（按字段名查找）
                    var searchComment= queryField.find("input[name='"+searchCondition+"']").val();
                    if(searchComment == null) {
                        queryField.append($(searchHtml));
                        var upHtml = queryField.find("i");
                        queryField.append(upHtml);
                    }
                }
            }
            form.render();
        }

        //确定事件
        window.determineQuery=function() {
            var checkStatus = table.checkStatus('formDialogTable'), data = checkStatus.data;
            if(JSON.stringify(data) === "[]") {
                layer.alert("还没有选择数据项！");
                return false;
            }
            var isSingle = combinationDialog.listDialog.issingle;
            var resultField = JSON.parse(combinationDialog.listDialog.resultfield);
            var count=0;
            var pkStr="ID";
            for(var p in data[0]){
                count++;
                if(count == 1 && (data[0][p].length == 32 || data[0][p]=='orgResourcesManager') && p.indexOf("ID")>0){
                    pkStr = p;
                    break;
                }
            }
            if(isSingle === 0) { //多选
                var returnData = [];
                var ids = [];

                for (var k= 0; k < data.length; k++) {
                    var resultJson = {};
                    ids.push(data[k][pkStr]);
                    for (var j = 0; j < resultField.length; j++) {
                        var returnField = resultField[j].field;
                        resultJson[returnField] = data[k][returnField];
                        if(j === resultField.length-1){
                            returnData.push(resultJson);
                        }
                    }
                }
                $("input[name='selectData']").val(JSON.stringify(returnData));
                $("input[name='selectDataIds']").val(ids);
            }else{
                var resultSingleJson = {};
                for (var p = 0; p < resultField.length; p++) {
                    resultSingleJson[resultField[p].field] = data[0][resultField[p].field];
                }
                $("input[name='selectData']").val(JSON.stringify(resultSingleJson));
                $("input[name='selectDataIds']").val(data[0][pkStr]);
            }

            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            if(isOpenJsonData === 'true') {
                layer.alert(JSON.stringify(data), function () {
                    parent.layer.close(index);
                });
            }
        };

        common.tableSort("formDialogTable");
    });
</script>
        <style>
            .outofHiding{
                width: 141px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        </style>
    </body>
</html>